import { getCurrentUserId } from '@/utils/backend/auth'
import { prisma } from '@/utils/backend/db'
import { HttpStatus } from '@/utils/httpStatus'
import { NextResponse } from 'next/server'

export async function DELETE(req: Request, { params }: { params: { id: string } }) {
	try {
		const chatId = Number(params.id)
		// ... 其余删除逻辑保持不变
		const token = req.headers.get('Authorization')?.replace('Bearer ', '')!
		const currentUserId = await getCurrentUserId(token)
		// 验证聊天室是否存在
		const chat = await prisma.privateChat.findUnique({
			where: { id: chatId },
		})

		if (!chat) {
			return NextResponse.json(
				{ success: false, message: '聊天室不存在' },
				{ status: HttpStatus.NOT_FOUND }
			)
		}

		// 验证用户是否是聊天参与者
		if (chat.user1Id !== currentUserId && chat.user2Id !== currentUserId) {
			return NextResponse.json(
				{ success: false, message: '无权操作此聊天室' },
				{ status: HttpStatus.FORBIDDEN }
			)
		}

		// 判断是哪一方删除
		const isUser1 = chat.user1Id === currentUserId

		// 软删除逻辑
		await prisma.$transaction([
			// 更新聊天室删除状态
			prisma.privateChat.update({
				where: { id: chatId },
				data: {
					// 只更新当前用户的删除状态
					...(isUser1 ? { deletedByUser1: true } : { deletedByUser2: true }),
					// 如果双方都删除了，才设置删除时间
					deletedAt: chat.deletedByUser1 || chat.deletedByUser2 ? new Date() : undefined,
				},
			}),
			// 更新消息删除状态
			prisma.privateMessage.updateMany({
				where: { chatId },
				data: {
					// 只更新当前用户的删除状态
					...(isUser1 ? { deletedByUser1: true } : { deletedByUser2: true }),
				},
			}),
		])

		return NextResponse.json({
			success: true,
			message: '删除成功',
		})
	} catch (error) {
		console.error('Delete chat failed:', error)
		return NextResponse.json(
			{ success: false, message: '删除聊天室失败' },
			{ status: HttpStatus.INTERNAL_SERVER_ERROR }
		)
	}
}
